// 提取重复的 DOM 操作为单独的函数
function getElementValueById(id) {
    return document.getElementById(id).value;
}

// 页面加载时获取用户信息并设置默认值
window.onload = function () {
    loadData();
    axios.get('/my/userinfo', {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.status === 0) {
            let userInfo = res.data.data;
            setDefaultValues(userInfo);
        }
    }).catch(err => {
        console.log(err);
    });
}

//加载动画
function showLoader() {
    let loader = document.querySelector(".loader");
    loader.style.display = "block";
}

function hideLoader() {
    let loader = document.querySelector(".loader");
    loader.style.display = "none";
}

// 在需要加载的地方调用显示加载动画的函数
function loadData(callback) {
    showLoader();

    setTimeout(function () {
        hideLoader();
        if (callback) {
            callback();
        }
    }, 2000);
}


// 设置输入框的默认值
function setDefaultValues(userInfo) {
    document.getElementById("name").value = userInfo.nickname;
    document.getElementById("studentID").value = userInfo.studentId;
    document.getElementById("major").value = userInfo.major;
    document.getElementById("class").value = userInfo.class;
    document.getElementById("email").value = userInfo.email;
}

function openModal() {
    var modal = document.getElementById("myModal");
    modal.style.display = "block";
}

function closeModal() {
    var modal = document.getElementById("myModal");
    modal.style.display = "none";
}

function saveChanges() {
    let name = getElementValueById("name");
    let studentID = getElementValueById("studentID");
    let major = getElementValueById("major");
    let classId = getElementValueById("class");
    let email = getElementValueById("email");

    if (!name || !studentID || !major || !classId || !email) {
        swal('修改失败', '请填写完整信息', 'error')
        return;
    }

    axios.post('/my/userinfo', {
        nickname: name,
        studentId: studentID,
        major: major,
        class: classId,
        email: email
    }, {
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        if (res.data.status === 0) {
            swal('修改成功', '即将返回', 'success');
            setTimeout(() => {
                closeModal();
                window.location.reload()
            }, 1000);
        }
    }).catch(err => {
        console.log(err);
        swal('修改失败', '请稍后再试', 'error');
    });
}